
#ifndef UTIL_HPP
#define UTIL_HPP

#include "nr_array.h"
#include "Matrix.hpp"
#include <iostream>
#include <sstream>
using namespace std;

namespace Util {
  //
  // conversion routines
  //
  template <class T> Vector<T> CSV2Vector ( istream& input )
  {
    string line;
    Vector<T> row;
    getline (input,line);
    // remove any blanks
    int p;
    while ( ( p = line.find(' ') ) != string::npos )
      line.erase(p,1);
    while ( ( p = line.find(',') ) != string::npos )
      line.replace(p,1," ");
    istringstream istr ( line );
    T tmp;
    while ( istr >> tmp )
      row.push_back(tmp);
    return row;
  }
  template <class T> Matrix<T> CSV2Matrix ( istream& input )
  {
    Matrix<T> RetMat;

    int cols=0;
    string line;
    while ( ! input.eof() )
      {
	Vector<T> row;
	getline (input,line);
	// remove any blanks
	int p;
	while ( ( p = line.find(' ') ) != string::npos )
	  line.erase(p,1);
	while ( ( p = line.find(',') ) != string::npos )
	  line.replace(p,1," ");
	istringstream istr ( line );
	T tmp;
	while ( istr >> tmp )
	  row.push_back(tmp);
	// check for consistency
	if ( row.size() > cols )
	  cols = row.size();
	else if ( row.size() < cols )
	  continue;

	RetMat.push_back(row);
      }
    return RetMat;
  }
  template <class T> NRMat<T> Matrix2NRMat ( const Matrix<T>& Mat )
  {
    NRMat<T> NRM ( Mat.row(), Mat.col() );
    for ( int r=0; r < Mat.row(); ++r )
      {
	for ( int c=0; c < Mat.col(); ++c )
	  NRM[r][c] = Mat[r][c];
      }
    return NRM;
  }
  template <class T> NRVec<T> Vector2NRVec ( const Vector<T>& Vec )
  {
    NRVec<T> NRV ( Vec.size() );
    for ( int i=0; i < Vec.size(); ++i )
      NRV[i] = Vec[i];
    return NRV;
  }
  template <class T> Matrix<T> NRMat2Matrix ( const NRMat<T>& NRM )
  {
    Matrix<T> Mat ( NRM.nrows(), NRM.ncols() );
    for ( int r=0; r < NRM.nrows(); ++r )
      {
	for ( int c=0; c < NRM.ncols(); ++c )
	  Mat[r][c] = NRM[r][c];
      }
    return Mat;
  }
  template <class T> Vector<T> NRVec2Vector ( const NRVec<T>& NRV )
  {
    Vector<T> Vec ( NRV.size() );
    for ( int i=0; i < NRV.size(); ++i )
      Vec[i] = NRV[i];
    return Vec;
  }
}
#endif
